<?php

/**
 * profile actions.
 *
 * @package    docplus.co.za
 * @subpackage profile
 * @author     Fox Matuku
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class profileActions extends sfActions
{

    /**
     * Executes register action
     *
     * @param sfRequest $request A request object
     */
    public function executeRegister(sfWebRequest $request)
    {
        
    }

    /**
     * Executes profile action
     *
     * @param sfRequest $request A request object
     */
    public function executeProfile(sfWebRequest $request)
    {
        
    }

    /**
     * Executes public action
     *
     * @param sfRequest $request A request object
     */
    public function executePublic(sfWebRequest $request)
    {
        $this->user = GfUserTable::getInstance()->findOneBySlug($request['slug']);
        $this->redirect('@' . strtolower($this->user->getType()) . '_profile_public?slug=' . $request['slug']);
    }

    /**
     * Executes signIn action
     *
     * @param sfRequest $request A request object
     */
    public function executeSignIn(sfWebRequest $request)
    {
        $this->command = "stay";
        $this->form = new SignInForm();
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    // seems everything has gone smoothly...so we can as well log them in :)
                    $this->getUser()->signin($this->form->getValue('user'), $this);

                    // or to the referer
                    // or to the homepage
                    $signinUrl = $this->getUser()->getReferer($request->getReferer());

                    return $this->redirect('' != $signinUrl ? $signinUrl : '@home');
                }
                catch (Exception $e)
                {
                    // invoke the event here so we get the error via email
                }
            }
        }
        else
        {
            // if we have been forwarded, then the referer is the current URL
            // if not, this is the referer of the current request
            $this->getUser()->setReferer($this->getContext()->getActionStack()->getSize() > 1 ? $request->getUri() : $request->getReferer());
        }
    }

    /**
     * Executes signInMini action
     *
     * @param sfRequest $request A request object
     */
    public function executeSignInMini(sfWebRequest $request)
    {
        $this->command = "stay";
        $this->form = new SignInForm();
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    // seems everything has gone smoothly...so we can as well log them in :)
                    $this->getUser()->signin($this->form->getValue('user'), $this);

                    $this->command = "redirect";
                }
                catch (Exception $e)
                {
                    // invoke the event here so we get the error via email
                }
            }
        }
    }

    /**
     * Executes signInModal action
     *
     * @param sfRequest $request A request object
     */
    public function executeSignInModal(sfWebRequest $request)
    {
        $this->command = "stay";
        $this->form = new SignInForm();
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    // seems everything has gone smoothly...
                    // so we can as well log them in :)
                    $this->getUser()->signIn($this->form->getValue('user'), $this);
                    $this->command = "redirect";
                }
                catch (Exception $e)
                {
                    // invoke the event here so we get the error via email
                }
            }
            else
            {
//                foreach ($this->form as $field)
//                {
//                    echo $field->renderLabel() . " " . $field->renderError() . "<br />";
//                }
//                die($this->form->renderGlobalErrors());
            }
        }
    }

    /**
     * Executes resetPasswordStepOne action
     *
     * @param sfRequest $request A request object
     */
    public function executeResetPasswordStepOne(sfWebRequest $request)
    {
        $this->command = "stay";
        $this->form = new ResetPasswordForm();
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    $user = GfUserTable::getInstance()->findOneByEmail($this->form->getValue('email'));
                    $this->forward404Unless($user);

                    // reset password and send it through to the user
                    $this->command = "done";

                    // set the password token and it's expiry datetime
                    $user->setPasswordToken(gfToolkit::random(12));
                    $user->setPasswordExpiryAt(date('Y-m-d H:i:s', strtotime('+30 minutes')));
                    $user->save();

//                    $mailer = new gfMailer(sfContext::getInstance(), sfContext::getInstance()->getEventDispatcher());
//                    $mailer->setTemplate('reset-password');
//                    $mailer->addValues(array(
//                        "USER" => $this->getUser()->getDpUser(),
//                        "PASSWORD_RESET_STEP_TWO_URL" => $this->generateUrl("profile_reset_password_step_two", array("password_token" => ""))
//                    ));
//                    $mailer->send();
                }
                catch (Exception $e)
                {
                    // invoke the event here so we get the error via email
                }
            }
        }
    }

    /**
     * Executes resetPasswordStepTwo action
     *
     * @param sfRequest $request A request object
     */
    public function executeResetPasswordStepTwo(sfWebRequest $request)
    {
        $this->passwordToken = $request->getParameter('password_token');
        $user = GfUserTable::getInstance()->findOneByPasswordToken($this->passwordToken);
        $this->forward404Unless($user);

        // set the current route
        $this->getUser()->setCurrentRoute("member_profile");

        $this->form = new myCredentialsForm(array(
                "user_id" => $user->getId(),
                "email" => $user->getEmail()),
                array(
                    "user" => $user,
                    "is_email_hidden" => true,
                    "is_password_required" => true
                )
        );

        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    $member = $this->form->save();
                    $this->getUser()->setFlash('notice', "You've successfully reset your password.");

                    $this->redirect("@home");
                }
                catch (Exception $e)
                {
                    // invoke the event here so we get the error via email
                }
            }
        }
    }

    /**
     * Executes resetPasswordMini action
     *
     * @param sfRequest $request A request object
     */
    public function executeResetPasswordModal(sfWebRequest $request)
    {
        $this->command = "stay";
        $this->form = new ResetPasswordForm();
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    $user = GfUserTable::getInstance()->findOneByEmail($this->form->getValue('email'));
                    $this->forward404Unless($user);

                    // reset password and send it through to the user
                    $this->command = "done";

                    // set the password token and it's expiry datetime
                    $user->setPasswordToken(gfToolkit::random(12));
                    $user->setPasswordExpiryAt(date('Y-m-d H:i:s', strtotime('+30 minutes')));
                    $user->save();
                }
                catch (Exception $e)
                {
                    // invoke the event here so we get the error via email
                }
            }
        }
    }

    /**
     * Executes signOut action
     *
     * @param sfRequest $request A request object
     */
    public function executeSignOut(sfWebRequest $request)
    {
        $this->getUser()->signOut();
        $this->redirect('/');
    }

    /**
     * Executes notificationSetting action
     *
     * @param sfRequest $request A request object
     */
    public function executeNotificationSetting(sfWebRequest $request)
    {
        // set the current route
        $this->getUser()->setCurrentRoute("member_profile");

        $this->notificationToken = $request->getParameter('notification_token');
        $user = GfUserTable::getInstance()->findOneByNotificationToken($this->notificationToken);
        $this->forward404Unless($user);

        // fetch the notification settings for this user
        $notificationSetting = $user->getNotificationSetting();

        if (!is_object($notificationSetting))
        {
            // save notification settings for this user
            $notificationSetting = new NotificationSetting();
            $notificationSetting->setUser($user);
            $notificationSetting->save();
        }

        $this->form = new NotificationSettingForm($notificationSetting);

        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    $this->form->save();
                    $this->getUser()->setFlash('notice', 'Your notification settings have been updated successfully.');

                    $this->redirect('@member_notification_setting=?notification_token=' . $this->notificationToken);
                }
                catch (Exception $e)
                {
                    // invoke the event here so we get the error via email
                }
            }
            else
            {
//                foreach ($this->form as $field)
//                {
//                    echo $field->renderLabel() . " " . $field->renderError() . "<br />";
//                }
//                die($this->form->renderGlobalErrors());
            }
        }
    }

}
